<template>
    <el-table ref="myTable" :data="tableData" style="width: 100%; height: 95%">
      <template v-for="(item,index) in tableConfig" :key="index">
        <el-table-column :prop="prop" :label="label"></el-table-column>
      </template>
    </el-table>
  </template>
  <script setup>
  import { ref, onMounted, onUnmounted, watch } from "vue";
  const tableData = [];
  const tableConfig = []
  const myTable = ref(null);
  let timer;
  let scrollTop = 0;
  let scrollDirection = 1; // 1 表示向下，-1 表示向上
  let isPause = false;
  const props = defineProps({
    autoScroll: { type: Boolean, default: true },
    speed: { type: Number, default: 0.5 },
  });
  watch(
    () => props.autoScroll,
    (newValue) => {
      console.log(newValue);
      if (newValue === false) {
        isPause = true;
        scrollContent();
      } else {
        isPause = false;
        scrollContent();
      }
    }
  );
  watch(
    () => props.speed,
    (newValue) => {
      scrollContent();
    }
  );
  onMounted(() => {
    if (props.autoScroll) {
      scrollContent();
    }
  });
  onUnmounted(() => {
    isPause = true;
    scrollContent();
  });
  const scrollContent = () => {
    if (isPause) {
      return;
    }
    // 拿到 table
    const table = myTable.value.layout.table.refs;
    // 拿到可以滚动的元素
    const tableWrapper = table.bodyWrapper.firstElementChild.firstElementChild;
    if (scrollTop > tableWrapper.scrollHeight - tableWrapper.clientHeight) {
      // 滚动到底部，暂停
      scrollTop = tableWrapper.scrollHeight - tableWrapper.clientHeight;
      tableWrapper.scrollTop = scrollTop;
      setTimeout(function () {
        scrollDirection = -1; // 更改滚动方向为向上
        scrollContent(); // 继续滚动
      }, 2000);
    } else if (scrollTop < 0) {
      // 滚动到顶部，暂停
      scrollTop = 0;
      tableWrapper.scrollTop = scrollTop;
      setTimeout(function () {
        scrollDirection = 1; // 更改滚动方向为向下
        scrollContent(); // 继续滚动
      }, 2000);
    } else {
      // 正常滚动
      scrollTop += scrollDirection * props.speed;
      tableWrapper.scrollTop = scrollTop;
      // 递归调用以继续滚动
      timer = requestAnimationFrame(scrollContent);
    }
  };
  </script>